package com.example.demo.Util;

import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

@Component
public class UpPhotoNameUtils {
    static String UserPicRoot = "static/";

    public String SaveUserPic(String LodPath , MultipartFile file) {

        //String contentType = file.getContentType();
        //限制文件格式


        String filename = String.valueOf(System.currentTimeMillis()) ;
        //先创建文件夹
        Calendar cad = Calendar.getInstance();
        String month = String.valueOf(cad.get(Calendar.MONTH) + 1);
        if (month.length() < 2) {
            month = "0" + month;
        }
        String day = String.valueOf(cad.get(Calendar.DAY_OF_MONTH));
        String SaveUserPicRoot = null;
        try {
            SaveUserPicRoot= ResourceUtils.getURL("classpath:").getPath()+UserPicRoot;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String RevPath = LodPath +"/"+ String.valueOf(cad.get(Calendar.YEAR)) +"/"+ month+"/"+day;
        String savePath = SaveUserPicRoot+RevPath;
//        System.out.println(savePath);
        String realsavePath = savePath.replace('/', '\\').substring(1,savePath.length());
        //System.out.println(realsavePath);
        //这个是为了拿到真实的存储地址，返回结果如下：C:\Users\31395\Desktop\WhiteHole\WhiteHoleBoot\target\classes\static\UserPic\2021\12\1

        File dirFile = new File(realsavePath);
        boolean  bFile = dirFile.exists();
        if(!bFile){
            dirFile.mkdirs();
        }



        RevPath = RevPath+"/"+ filename + file.getOriginalFilename();
        savePath = (SaveUserPicRoot+RevPath);

        try {
            file.transferTo(new File(savePath));
        } catch (IOException e) {
            e.printStackTrace();
        }

       // System.out.println("savePath"+savePath);

        return "/" + savePath;
    }


}
